const { Cart } = require("../models/appUser");

module.exports = {
  // 增删改查
  async addCart(req, res) {
    const appUserId = req.userId;
    const { goodId, skuId, number } = req.body;
    const data = await Cart.create({
      appUserId: appUserId,
      goodId: goodId,
      skuId: skuId,
      number: number,
    });
    res.json({
      code: 200,
      data: data,
    });
  },
  async deleteCart(req, res) {
    const { id } = req.params;
    const appUserId = req.userId;
    const data = await Cart.destroy({
      where: {
        id: id,
        appUserId: appUserId,
      },
    });
    res.json({
      code: 200,
      data: data,
    });
  },
  async updateCart(req, res) {
    const { id } = req.params;
    const appUserId = req.userId;
    const { number } = req.body;
    const data = await Cart.update(
      {
        number: number,
      },
      {
        where: {
          id: id,
          appUserId: appUserId,
        },
      }
    );
    res.json({
      code: 200,
      data: data,
    });
  },
  async getCart(req, res) {
    const appUserId = req.userId;
    const data = await Cart.findAll({
      where: {
        appUserId: appUserId,
      },
      include: {
        all: true,
      },
    });
    res.json({
      code: 200,
      data: data,
    });
  },
  async getCartById(req, res) {
    const { id } = req.params;
    const appUserId = req.userId;
    const data = await Cart.findOne({
      where: {
        id: id,
        appUserId: appUserId,
      },
    });
    res.json({
      code: 200,
      data: data,
    });
  },
  // 清空购物车
  async clearCart(req, res) {
    const appUserId = req.userId;
    const data = await Cart.destroy({
      where: {
        appUserId: appUserId,
      },
    });
    res.json({
      code: 200,
      data: data,
    });
  },
};
